package us.kg.kotoriforest.spring.processor;

import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import us.kg.kotoriforest.spring.annotation.UUID;
import us.kg.kotoriforest.spring.util.UUIDUtil;

import java.lang.reflect.Field;

/**
 * {@link UUID}注解的BeanPostProcessor
 * 给IOC容器中的Bean的属性赋值
 *
 * @author Kotori rotroutine@163.com
 * @since 2025/1/26
 */
@Component // BeanPostProcessor在IOC容器中才能起作用
public class UUIDAnnotationBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        // System.out.println("UUIDAnnotationBeanPostProcessor postProcessBeforeInitialization");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        for (Field field : bean.getClass().getDeclaredFields()) {
            UUID uuid = field.getAnnotation(UUID.class);
            if (null != uuid) {
                field.setAccessible(true);
                try {
                    field.set(bean, UUIDUtil.getUUID(uuid.containsDelimiter()));
                } catch (IllegalAccessException e) {
                    throw new BeanCreationException("UUID注解赋值失败", e);
                }
            }
        }

        return bean;
    }
}
